// SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
// SPDX-License-Identifier: Apache-2.0

package roadmap_qa_api_serv

import (
	"context"
	"time"

	"gitcode.com/lvupclub/lvup-api/dao"
	"gitcode.com/lvupclub/lvup-api/dao/roadmap_dao"
	"gitcode.com/lvupclub/lvup-api/dao/user_dao"
	"gitcode.com/lvupclub/proto-gen-go.git/src/roadmap_qa_api"
	"github.com/google/uuid"
)

func (apiImpl *RoadmapQaApiImpl) AddContent(ctx context.Context, req *roadmap_qa_api.AddContentRequest) (*roadmap_qa_api.AddContentResponse, error) {
	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_qa_api.AddContentResponse{
			Code:   roadmap_qa_api.AddContentResponse_CODE_WRONG_SESSION,
			ErrMsg: "会话不存在",
		}, nil
	}
	roadmapItem, err := roadmap_dao.RoadmapInfoDao.Get(ctx, req.RoadmapId)
	if err != nil {
		return &roadmap_qa_api.AddContentResponse{
			Code:   roadmap_qa_api.AddContentResponse_CODE_NO_ROADMAP,
			ErrMsg: "会话不存在",
		}, nil
	}
	threadItem, err := roadmap_dao.ThreadInfoDao.Get(ctx, req.RoadmapId, req.ThreadId)
	if err != nil {
		return &roadmap_qa_api.AddContentResponse{
			Code:   roadmap_qa_api.AddContentResponse_CODE_NO_THREAD,
			ErrMsg: "问答会话不存在",
		}, nil
	}
	if !(roadmapItem.OwnerUserId == sessItem.UserId || threadItem.AskUserId == sessItem.UserId) {
		return &roadmap_qa_api.AddContentResponse{
			Code:   roadmap_qa_api.AddContentResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}
	if threadItem.ThreadState == roadmap_qa_api.THREAD_STATE_THREAD_STATE_CLOSE {
		return &roadmap_qa_api.AddContentResponse{
			Code:   roadmap_qa_api.AddContentResponse_CODE_NO_PERMISSION,
			ErrMsg: "没有权限",
		}, nil
	}

	nowTime := time.Now().UnixMilli()
	contentId := uuid.NewString()

	dbSess, err := dao.StartSession()
	if err != nil {
		return nil, err
	}
	defer dao.EndSession(dbSess)

	ret, err := dbSess.WithTransaction(ctx, func(sessCtx context.Context) (interface{}, error) {
		err = roadmap_dao.ThreadContentDao.Insert(sessCtx, &roadmap_dao.ThreadContentInfoDbItem{
			ContentId: contentId,
			RoadmapId: req.RoadmapId,
			ThreadId:  req.ThreadId,
			Content:   req.Content,
			OptUserId: sessItem.UserId,
			OptTime:   nowTime,
		})
		if err != nil {
			return nil, err
		}
		err = roadmap_dao.ThreadInfoDao.UpdateUpdateTime(sessCtx, req.RoadmapId, req.ThreadId, nowTime)
		if err != nil {
			return nil, err
		}
		return &roadmap_qa_api.AddContentResponse{
			Code:      roadmap_qa_api.AddContentResponse_CODE_OK,
			ContentId: contentId,
		}, nil
	})
	if err != nil {
		return nil, err
	}
	return ret.(*roadmap_qa_api.AddContentResponse), nil
}

func (apiImpl *RoadmapQaApiImpl) ListContent(ctx context.Context, req *roadmap_qa_api.ListContentRequest) (*roadmap_qa_api.ListContentResponse, error) {
	emptyList := []*roadmap_qa_api.ThreadContentInfo{}

	sessItem, ok := dao.CacheDao.GetSession(ctx, req.SessionId)
	if !ok {
		return &roadmap_qa_api.ListContentResponse{
			Code:        roadmap_qa_api.ListContentResponse_CODE_WRONG_SESSION,
			ErrMsg:      "会话不存在",
			ContentList: emptyList,
		}, nil
	}
	roadmapItem, err := roadmap_dao.RoadmapInfoDao.Get(ctx, req.RoadmapId)
	if err != nil {
		return &roadmap_qa_api.ListContentResponse{
			Code:        roadmap_qa_api.ListContentResponse_CODE_NO_ROADMAP,
			ErrMsg:      "会话不存在",
			ContentList: emptyList,
		}, nil
	}
	threadItem, err := roadmap_dao.ThreadInfoDao.Get(ctx, req.RoadmapId, req.ThreadId)
	if err != nil {
		return &roadmap_qa_api.ListContentResponse{
			Code:        roadmap_qa_api.ListContentResponse_CODE_NO_THREAD,
			ErrMsg:      "问答会话不存在",
			ContentList: emptyList,
		}, nil
	}
	if !(roadmapItem.OwnerUserId == sessItem.UserId || threadItem.AskUserId == sessItem.UserId) {
		return &roadmap_qa_api.ListContentResponse{
			Code:        roadmap_qa_api.ListContentResponse_CODE_NO_PERMISSION,
			ErrMsg:      "没有权限",
			ContentList: emptyList,
		}, nil
	}

	count, err := roadmap_dao.ThreadContentDao.Count(ctx, req.ThreadId)
	if err != nil {
		return nil, err
	}
	contentItemList, err := roadmap_dao.ThreadContentDao.List(ctx, req.ThreadId, int64(req.Offset), int64(req.Limit))
	if err != nil {
		return nil, err
	}
	//补全用户信息
	userIdList := []string{}
	for _, contentItem := range contentItemList {
		userIdList = append(userIdList, contentItem.OptUserId)
	}
	userItemList, err := user_dao.UserInfoDao.ListById(ctx, userIdList)
	if err != nil {
		return nil, err
	}
	userItemMap := map[string]*user_dao.UserInfoDbItem{}
	for _, userItem := range userItemList {
		userItemMap[userItem.UserId] = userItem
	}
	//生成结果
	contentList := []*roadmap_qa_api.ThreadContentInfo{}
	for _, contentItem := range contentItemList {
		content := contentItem.ToThreadContentInfo()
		userItem, ok := userItemMap[contentItem.OptUserId]
		if ok {
			content.OptUserDisplayName = userItem.BasicInfo.DisplayName
			content.OptUserLogoUri = userItem.BasicInfo.LogoUri
		}
		contentList = append(contentList, content)
	}

	return &roadmap_qa_api.ListContentResponse{
		Code:        roadmap_qa_api.ListContentResponse_CODE_OK,
		TotalCount:  count,
		ContentList: contentList,
	}, nil
}
